//
//  YHFocusCollectionView.m
//  FAKER
//
//  Created by dllo on 15/11/10.
//  Copyright © 2015年 YHLai. All rights reserved.
//

#import "YHFocusCollectionView.h"
#import "FitHeader.h"
#import "AllHeader.h"
#import "YHFocusCollectionCell.h"

@implementation YHFocusCollectionView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //查找数据库
        _manager = [CoreDataManager shareManager];
        [self searchCoreData];
        
        [self createViews];
    }
    return self;
}

- (void)createViews
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH - 4) / 3, (SCREEN_WIDTH - 4) / 3);
    flowLayout.minimumInteritemSpacing = 1.5 * FITWIDTH;
    flowLayout.minimumLineSpacing = 1.8 * FITWIDTH;
    
    _collectionView = [[BaseClassCollectionView alloc] initWithFrame:self.frame collectionViewLayout:flowLayout];
//    _collectionView.backgroundColor = [UIColor colorWithRed:0.94 green:0.94 blue:0.94 alpha:1];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    [self addSubview:_collectionView];
    [_collectionView registerClass:[YHFocusCollectionCell class] forCellWithReuseIdentifier:@"focus"];
}

#pragma mark - collectionView
#pragma mark cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataSourceArray.count;
}
#pragma mark cell样式
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    YHFocusCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"focus" forIndexPath:indexPath];
    cell.focus = _dataSourceArray[indexPath.row];
    cell.layer.transform = CATransform3DMakeScale(0.3, 0.3, 0.1);
    [UIView animateWithDuration:0.5 animations:^{
        cell.layer.transform = CATransform3DMakeScale(1, 1, 0.1);
    }];
    return cell;
}
#pragma mark cell点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.jumpDelegate yhJump:_dataSourceArray[indexPath.row]];
}

#pragma mark - 重写属性set
- (void)setIsReloadData:(BOOL)isReloadData
{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"focus"]) {
        [self searchCoreData];
        [_collectionView reloadData];
        
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"focus"];
    }
}

#pragma mark - 查询数据库
- (void)searchCoreData
{
    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Focus"];
    _dataSourceArray = [NSArray arrayWithArray:[_manager.managedObjectContext executeFetchRequest:fetchRequest error:nil]];
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
